<template>
  <main-content
    :title="mode === 'create' ? '新建优惠券' : '编辑优惠券'"
    back
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      :label-width="120"
    >
      <el-form-item
        label="优惠券名称"
        prop="name"
      >
        <el-input
          v-model.trim="form.name"
          placeholder="请输入优惠券名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="优惠券类型">
        {{ getCouponTypeName(couponDetail?.couponType) }}
      </el-form-item>
      <el-form-item label="优惠券规则">
        <template v-if="couponDetail?.couponType === 1">
          消费满{{ couponDetail?.discountRule?.fullPrice }}，立减{{ couponDetail?.discountRule?.reducePrice }}元
        </template>
        <template v-if="couponDetail?.couponType === 2">
          消费满{{ couponDetail?.discountRule?.fullPrice }}，可享受折扣{{ couponDetail?.discountRule?.discount }}折（折扣比例:原价为1，0.99即为九九折）
        </template>
        <template v-if="couponDetail?.couponType === 3">
          使用范围商品任选一件兑换
        </template>
      </el-form-item>
      <el-form-item label="使用范围">
        <template v-if="couponDetail?.useRange === 1">
          {{ getCouponUseRangeLabel(couponDetail?.useRange) }} {{ couponDetail?.businessName ? `(${couponDetail?.businessName})` : '' }}
        </template>

        <template v-if="couponDetail?.useRange === 2">
          {{ getCouponUseRangeLabel(couponDetail?.useRange) }} ({{ mallConfig.mallName }})
        </template>

        <template v-if="couponDetail?.useRange === 3">
          {{ getCouponUseRangeLabel(couponDetail?.useRange) }} ({{ mallConfig.mallName }} - 部分商品)
        </template>

        <template v-if="couponDetail?.useRange === 4">
          {{ getCouponUseRangeLabel(couponDetail?.useRange) }} ({{ mallConfig.mallName }} - 部分商品分类)
        </template>
      </el-form-item>
      <el-form-item label="领取时间">
        {{ formatTime(couponDetail?.receiveStartTime) }} 至 {{ formatTime(couponDetail?.receiveEndTime) }}
        <template v-if="couponDetail?.receiveType === 0">
          领取时间内，均可领取
        </template>
        <template v-if="couponDetail?.receiveType === 1">
          领取时间内，每天{{ couponDetail?.receiveRangeStartTime }} 至 {{ couponDetail?.receiveRangeEndTime }} 
        </template>
        <template v-if="couponDetail?.receiveType === 2">
          领取时间内，每周 {{ couponDetail?.receiveWeekDay }} {{ couponDetail?.receiveRangeStartTime }} 至 {{ couponDetail?.receiveRangeEndTime }} 
        </template>
        <template v-if="couponDetail?.receiveType === 3">
          领取时间内，每月 {{ couponDetail?.receiveMonth }} 日 {{ couponDetail?.receiveRangeStartTime }} 至 {{ couponDetail?.receiveRangeEndTime }} 
        </template>
      </el-form-item>
      <el-form-item label="优惠券图片">
        <Upload
          v-model="form.thumbnailUrl"
          list-type="picture-card"
          file-path="pointsMall/"
          @change="onChange"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </Upload>
      </el-form-item>
      <el-form-item
        label="优惠券批次"
        prop="couponProducts"
      >
        <el-select
          @change="handleBatchSelected"
        >
          <el-option
            v-for="item in couponDetail?.batchInfoEntities"
            :key="item.id"
            :label="item.couponBatchName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="已选择的批次"
        prop="couponBatchTable"
      >
        <el-table :data="form.products">
          <el-table-column
            label="批次ID"
            prop="batchId"
            width="200"
          />
          <el-table-column
            label="批次名称"
            prop="name"
            width="200"
          >
            <template #default="props">
              <el-input
                v-model="props.row.name"
                placeholder="请输入批次名称"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="使用开始时间"
            width="200"
          >
            <template #default="props">
              <template v-if="props.row.takeEffectType === 0">
                领取后立即使用
              </template>
              <template v-if="props.row.takeEffectType === 1">
                领取后第二天可使用
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="使用结束时间"
            width="220"
          >
            <template #default="props">
              <template v-if="props.row.useType === 0">
                固定时间内均可使用
              </template>
              <template v-if="props.row.useType === 1">
                相对开始时间 {{ props.row.useDayNum }} 天内可使用 (1 表示当天失效)
              </template>
              <template v-if="props.row.useType === 2">
                相对开始时间 {{ props.row.useMonthNum }} 月内可使用(1 表示当月月底失效,2表示次月月底失效,依此类推)
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-if="mode === 'create'"
            label="可配置库存"
            prop="couponTotalNum"
            width="150"
          />
          <el-table-column
            v-if="mode === 'create'"
            label="设置库存"
            width="200"
          >
            <template #default="props">
              <el-input
                v-model="props.row.addOrDeductionStockCount"
                placeholder="输入库存"
                @blur="(value) => handleBlur(props.row, 'addOrDeductionStockCount')"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="mode === 'edit'"
            label="可发放张数"
            prop="couponTotalNum"
            width="150"
          />
          <el-table-column
            v-if="mode === 'edit'"
            label="总库存/剩余库存"
            prop="couponTotalNum"
            width="150"
          >
            <template #default="props">
              {{ props.row.totalStock }}/{{ props.row.stock }}
            </template>
          </el-table-column>

          <el-table-column
            v-if="mode === 'edit'"
            label="配置发放张数"
            width="350"
          >
            <template #default="props">
              <count-adjust
                v-model="props.row.addOrDeductionStockCount"
                :show-symbol="props.row.isCreatedThisTime ? '+' : '+-'"
                @change="validateTable"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template #default="props">
              <el-button
                type="danger"
                @click="deleteBatch(props.row, props.row.index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item
        label="售价"
        prop="salePrice"
      >
        <div class="inline-form-item">
          <el-input v-model="form.payOfCurrencyCount">
            <template #append>
              积分
            </template>
          </el-input>
          <el-input v-model="form.payPrice__yuan">
            <template #append>
              元
            </template>
          </el-input>
        </div>
      </el-form-item>

      <el-form-item
        label="领取次数"
        prop="productLimit"
        class="common-form-item"
      >
        <el-input v-model="form.productLimit">
          <template #append>
            张/人
          </template>
        </el-input>
      </el-form-item>

      <!-- <el-form-item label="商品审核">
        <el-switch
          active-text="开启"
          inactive-text="关闭"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item> -->

      <el-form-item label="使用说明">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="5"
        />
      </el-form-item>
    </el-form>

    <template #fixed-bottom>
      <div class="submit-wrapper">
        <el-button
          type="primary"
          @click="submit"
        >
          提交
        </el-button>
      </div>
    </template>
  </main-content>
</template>

<script setup lang="ts">
import type { Ref } from "vue"
import type { IMallCouponDefineInfo } from "@/api/modules/pointsMall"
import type { ICouponBatchManageRow } from "@/api/modules/marketingTool"
import type { InternalRuleItem } from 'async-validator';
import moment from "moment"
import { getCouponDefineInfo, getGoodsDetail, editGoods } from "@/api/pointsMall"
import { useCouponType } from "@/views/marketingTool/compositions/useCouponType"
import { useCouponUseRange } from "@/views/marketingTool/compositions/useCouponUseRange"
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig"
import { positiveInteger, positiveNumber_decimal$2, positiveInteger_0  } from "@/utils/commonRegexp" 
import { addGoods } from "@/api/pointsMall";


const route = useRoute()
const router = useRouter()
const { getCouponTypeName } = useCouponType()
const { getCouponUseRangeLabel } = useCouponUseRange()
const { mallConfig } = useMallConfig()

const mode = computed(() => {
  let _mode = ''
  if (route.path.includes('edit')) {
    _mode = "edit"
  } else {
    _mode = "create"
  }

  return _mode
})

const DefaultCouponThumbnailUrl = 'https://minio.lianhaikeji.com/marketing/pointsMall/1694423169000eYRkFD6J.png'

const formRef = ref({
  productLimit: 1,
  thumbnailUrl: "", 
})
const formRules = ref({
  name: [ {
    required: true,
    message: "请输入优惠券名称",
    trigger: 'blur'
  } ],
  thumbnailUrl: [ {
    required: true,
    message: "请上传图片",
    trigger: "change"
  } ],
  couponProducts: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (form.value.products <= 0) {
        callback("请选择优惠券批次")
        return
      }
      callback()
    }
  } ],
  couponBatchTable: [ {
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      let verifyFlag = 1
      for (let i = 0; i < form.value.products.length; i++) {
        const batchItem = form.value.products[i]
        const _batchIdentifier = `表格第${i + 1}行`

        if (!batchItem.name) {
          callback(`请填写${_batchIdentifier}批次中的批次名称`)
          verifyFlag = 0
          break;
        }

        // 新建时必填  
        // 编辑优惠券，且新增了批次
        if (mode.value === 'create' || (mode.value === 'edit' && batchItem.isCreatedThisTime)) {
          if (!positiveInteger.test(batchItem.addOrDeductionStockCount)) {
            callback(`${_batchIdentifier}批次中设置的库存需为正整数`)
            verifyFlag = 0
            break;
          }

          if (batchItem.addOrDeductionStockCount > batchItem.couponTotalNum) {
            callback(`${_batchIdentifier}批次中设置的库存不能大于可发放库存`)
            verifyFlag = 0
            break;
          }
        }

        // 编辑既有批次时有输入就校验
        if (mode.value === 'edit' && !isEmpty(batchItem.addOrDeductionStockCount)) {
          // console.log('verify batchItem', batchItem)

          if (batchItem.addOrDeductionStockCount < 0 && Math.abs(batchItem.addOrDeductionStockCount) > batchItem.stock) {
            callback(`${_batchIdentifier}批次中减少的库存不能大于剩余库存`)
            verifyFlag = 0
            break;
          }

          if (batchItem.addOrDeductionStockCount > batchItem.couponTotalNum) {
            callback(`${_batchIdentifier}批次中增加的库存不能大于可发放库存`)
            verifyFlag = 0
            break;
          }
        }
      }

      if (!verifyFlag) {
        return
      }

      callback()
    }
  } ],
  salePrice: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (!positiveInteger_0.test(form.value.payOfCurrencyCount)) {
        callback('积分需大于等于0')
        return
      }

      if (!positiveNumber_decimal$2.test(form.value.payPrice__yuan)) {
        callback('金额需大于0，且保留2位小数')
        return
      }

      callback()
    }
  } ],
  productLimit: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (!positiveInteger.test(form.value.productLimit)) {
        callback(`领取次数需为正整数`)
        return
      }

      callback()
    }
  } ]

})
const form = ref({
  products: [], // 优惠券批次
})

const handleBlur = (assignObject, key) => {
  if (assignObject[key] !== null && assignObject[key] !== undefined) {
    assignObject[key] = assignObject[key].trim()
  }
}

const formatTime = (timestamp: number) => {
  return timestamp ? moment(timestamp).format("YYYY.MM.DD HH:mm:ss") : ''
}

const isEmpty = (val:unknown) => val === undefined || val === null || val === ""

const handleBatchSelected = (id: number) => {
  const batchItem = couponDetail?.value?.batchInfoEntities.find(item => item.id === id)
  if (batchItem) {
    const _batchItem = JSON.parse(JSON.stringify(batchItem))
    _batchItem.name = _batchItem.couponBatchName
    _batchItem.storeProductId = _batchItem.id
    _batchItem.isCreatedThisTime = true // 标识是否是本次编辑时新建的批次
    _batchItem.batchId = _batchItem.id // 优惠券批次ID
    _batchItem.id = null // 商品规格ID
    form.value.products.push(_batchItem)
  }
}

const deleteBatch = (row: ICouponBatchManageRow, index: number) => {
  form.value.products.splice(index, 1)
}

const validateTable = () => {
  formRef.value.validateField('couponBatchTable')
}

const submit = () => {
  console.log("提交！！！")
  console.log("form.value", form.value)
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log("表单验证通过")
      form.value.mallId = mallConfig.value.id
      form.value.storeGoodsId = couponDetail.value.id
      form.value.type = 'systemCoupon' // 固定
      form.value.payPrice = form.value.payPrice__yuan * 100 // 元 转 分
      form.value.stock = form.value.products.reduce((total, current) => total += Number(current.addOrDeductionStockCount), 0)
      form.value.products.forEach(item => {
        item.payPrice = form.value.payPrice
        item.payOfCurrencyCount = form.value.payOfCurrencyCount
      })
      
      let rs
      if (mode.value === 'edit') {
        rs = await editGoods(form.value)
      } else {
        rs = await addGoods(form.value)
      }

      if ( rs.code === 200 ) {
        ElMessage.success("保存成功")
        router.back()
      }
    }
  })
}

const couponDetail:Ref<IMallCouponDefineInfo | undefined> = ref()
const _getCouponDetail = async (couponDefineId: string) => {
  const rs = await getCouponDefineInfo({
    id: couponDefineId as string,
  })

  if (rs.code !== 200) {
    return
  }

  couponDetail.value = rs.payload
}


const goodsDetail = ref()
const _getGoodsDetail = async () => {
  const rs = await getGoodsDetail({
    id: <string>route.query.id, // 商城优惠券已存在的优惠券id
  })

  if (rs.code === 200) {
    goodsDetail.value = rs.payload
  }
}

const echoFormForEdit = () => {
  couponDetail.value.discountRule = JSON.parse(couponDetail.value.discountRule)

  form.value = goodsDetail.value
  form.value.payPrice__yuan = goodsDetail.value.payPrice / 100 // 分 转 元

  form.value.products = form.value.products.map(productItem => {
    const matchedBatchItem = couponDetail.value.batchInfoEntities.find(batchItem => productItem.storeGoodsId === batchItem.couponDefineId)
    return {
      ...matchedBatchItem,
      batchId: matchedBatchItem.id,
      name: productItem.name,
      stock: productItem.stock,
      totalStock: productItem.totalStock,
      id: productItem.id
    }
  })
}

const echoFormForCreate = () => {
  couponDetail.value.discountRule = JSON.parse(couponDetail.value.discountRule)
  form.value.name = couponDetail.value.couponName

  if (!couponDetail.value.thumbnailUrl) {
    form.value.thumbnailUrl = DefaultCouponThumbnailUrl
  }
}

onMounted(async () => {
  if (mode.value === 'edit') {
    // EDIT
    await _getGoodsDetail()
    await _getCouponDetail(goodsDetail.value.storeGoodsId)
    echoFormForEdit()
  } else {
    // CREATE
    await _getCouponDetail(<string>route.query.couponDefineId)
    echoFormForCreate()
  }
})
  
</script>

<style scoped lang="scss">
.inline-form-item {
  display: inline-flex;
  align-items: center;
  word-break: keep-all;
}

.submit-wrapper {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.common-form-item) {
  .el-input {
    width: 253px;
  }
}
</style>